<?
/*
  Project     : 48c6c450f1a4a0cc53d9585dc0fee742
  Created on  : Mar 16, 2013, 11:29:15 PM
  Author      : Truong Khuong - khuongxuantruong@gmail.com
  Description :
  Purpose of the stylesheet follows.
 */

class auth_backend extends CI_Module {

    public $controller;
    public $auth_login_uri;
    public $privilege = -1;

    function __construct() {
        parent::__construct();
        $this->load->model("backend/auth_model");
        $this->controller = $this->router->fetch_class();
        $this->auth_login_uri = site_url("service/auth/login") . '?state=' . uri_string();
        $this->access_denied_uri = site_url("service/auth/denied") . '?state=' . uri_string();
        $this->isAjax = $this->input->is_ajax_request();
    }

    function login() {
        //$this->check_login();
        if (!isset($_SESSION["auth"]["user"])) {
            if ($this->isAjax) {
                if ($this->input->get_post('ajaxtype') === 'json') {
                    $R["result"] = -903;
                    $R["message"] = ascii_to_entities("You must be login.");
                    die(json_encode($R));
                } else {
                    die("You must be login.");
                }
            } else {
                redirect($this->auth_login_uri); //die("You must be login.");
            }
        }
        return $this;
    }

    function check_login() {
        $_password = $this->input->post("password");
        $_username = $this->input->post("username");
        $R["result"] = -998;
        $R["message"] = ascii_to_entities("Access is denied - Request invalid.");
        if (isset($_SESSION["auth"]["user"])) {
            $R["result"] = 1;
            $R["message"] = ascii_to_entities("Valid login.");
        //} elseif (!isset($_SESSION['auth']['oauth'])) {
        //    $R["result"] = -991;
        //    $R["message"] = ascii_to_entities("Authorized API Access, OAuth don't allow.");
        //    goto result;
        } elseif ($_password != false && $_username !=false) {
		
			if(!isset($_SESSION["logintry"]))$_SESSION["logintry"]=0;
			$_SESSION["logintry"]++;
			if($_SESSION["logintry"]>3){
				if(!isset($_SESSION["logintrytime"]))$_SESSION["logintrytime"]=time();
				$timedelay=60*15-(time("now")-$_SESSION["logintrytime"]);
				if( $timedelay<=0){
					$_SESSION["logintry"]=0;
					unset($_SESSION["logintrytime"]);
				}else{
					$p=floor($timedelay/60);
					$p=$p>0?"$p minute ":"";
					$s=$timedelay%60;
					$R["result"]     =   -999;
					$R["message"]    =   ascii_to_entities("[Access Denied] Sorry, there have been more than 5 failed login<br/>attempts for this account.<br/>
						It is temporarily blocked in 15 minutes.<br/>
						Remaining time : $p$s second.
						");
					goto result;
				}
			}
		
		
            //$_username = $_SESSION['auth']['oauth']['email'];
            $_name = $_username;//$_SESSION['auth']['oauth']['name'];
            $user = $this->auth_model->getuser("$_username");
            if ($user != null) {
                if ($user->ause_password != md5($_username . $_password . $user->ause_secretkey)) {
                    $_name = $user->ause_name;
                    $R["result"] = -906;
                    $R["message"] = ascii_to_entities("Login failed for user '$_name'.");
                    goto result;
                }
                if ($user->ause_delete !== null) {
                    $R["result"] = -901;
                    $R["message"] = ascii_to_entities("Valid login but user have been deleted.");
                    goto result;
                }
                if ($user->ause_status === "true") {
                    unset($user->ause_password);
                    //unset($user->ause_salt);
                    unset($user->ause_secretkey);
                    $_SESSION["auth"]["user"] = $user;
                    //$this->session->set_userdata('auth', $_SESSION["auth"]);
                    $tmp = $this->auth_model->getprivileges($user->ause_id);
                    $privileges = array();
                    if ($tmp !== null)
                        foreach ($tmp as $pve) {
                            $privileges[$pve->apri_key] = $pve;
                        }
                    $_SESSION["auth"]["privileges"] = $privileges;
                    $R["result"] = 1;
                    $R["message"] = ascii_to_entities("Valid login.");
					$_SESSION["logintry"]=0;
                } else {
                    $R["result"] = -902;
                    $R["message"] = ascii_to_entities("Valid login but user is not active.");
                    goto result;
                }
            } else {
                $R["result"] = -904;
                $R["message"] = ascii_to_entities("User does't exist or invalid user.");
                goto result;
            }
        }
        result:
        return $R;
    }

    function verify() {
        
    }

    function crypt() {
        
    }

    function privilege() {
        if (!isset($_SESSION["auth"]["privileges"]))
            goto access_denied;
        $privileges = $_SESSION["auth"]["privileges"];
        if (!isset($privileges[$this->controller]))
            goto access_denied;
        $this->privilege = $privileges[$this->controller];
        if ($this->privilege->aupr_permission == 0)
            goto access_denied;
        return $this;
        access_denied:
        if ($this->isAjax) {
            $R["result"] = -903;
            $R["message"] = ascii_to_entities(
                    "Access is denied for user \"" . $_SESSION["auth"]["user"]->ause_name . "\".<br/>
                    This function to requires an administrative account.<br/>
                    Please check your authority, and try again."
            );
            if ($this->input->get_post('ajaxtype') === 'json') {
                die(json_encode($R));
            } else {
                die($R["message"]);
            }
        } else {
            redirect($this->access_denied_uri); //echo("Access denied.");
        }
    }

}

?>
